package com.wuzf.mall.net.callback

import android.os.Handler
import com.wuzf.mall.global.GlobalKeys
import com.wuzf.mall.global.Mall
import com.wuzf.mall.loading.MallLoader
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class RequestCallbacks(
    private val success: ISuccess?,
    private var failure: IFailure?,
    private var error: IError?,
    private var complete: IComplete?
) : Callback<String> {

    private val handler = Mall.getConfiguration<Handler>(GlobalKeys.HANDLER)

    override fun onResponse(call: Call<String>, response: Response<String>) {
        if (call.isExecuted) {
            if (response.isSuccessful)
                success?.result(response.body())
            else
                error?.result(response.message())
        }
        requestFinish()
    }

    override fun onFailure(call: Call<String>, t: Throwable) {
        error?.result(t.message)
        requestFinish()
    }

    private fun requestFinish() {
        val time = Mall.getConfiguration<Long>(GlobalKeys.DELAY_TIME)
        handler.postDelayed({ MallLoader.stopLoading() }, time)
    }
}